/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package view;

import java.awt.Component;
import java.awt.Image;
import java.util.ArrayList;
import javax.swing.*;
import javax.swing.table.*;

/**
 *
 * @author DAVINCI
 */
public class IngresoM_ij extends javax.swing.JDialog {

    private int filas;
    private int columnas;
    private TableModel modeloBloques;
    private TableModel modeloDiferentes;
    private TableModel modeloIguales;
    private TableModel modeloTratamientos;
    private ImageIcon imageIcon = new ImageIcon(getClass().getResource("/view/gui/m_ij.png"));
    private Image icono = imageIcon.getImage();
    private boolean resultado;
    public Integer matrizM[][];
    private int metodo;
    static int MBLOQUES = 1;
    static int MDIFERENTES = 2;
    static int MIGUALES = 3;
    static int MTRATAMIENTOS = 4;

    public ButtonGroup getGrupoOpciones() {
        return grupoOpciones;
    }

    public boolean hayResultado() {
        return resultado;
    }

    public JRadioButton getRadioBloque() {
        return radioBloque;
    }

    public JRadioButton getRadioDiferentes() {
        return radioDiferentes;
    }

    public JRadioButton getRadioIguales() {
        return radioIguales;
    }

    public JRadioButton getRadioTratamiento() {
        return radioTratamiento;
    }

    public int getMetodo() {

        return metodo;
    }

    public Integer[][] getMatrizM() {
        return matrizM;
    }

    public void setMatrizM(Integer[][] matrizM) {
        this.matrizM = matrizM;
    }

    /**
     * Creates new form IngresoM_ij
     */
    public IngresoM_ij(java.awt.Frame parent, boolean modal, int filas, int columnas) {
        super(parent, modal);
        this.filas = filas;
        this.columnas = columnas;
        initComponents();

        grupoOpciones.add(radioBloque);
        grupoOpciones.add(radioDiferentes);
        grupoOpciones.add(radioIguales);
        grupoOpciones.add(radioTratamiento);
        radioIgualesActionPerformed(null);
        matrizM=new Integer[filas][columnas];

    }

    public void packColumns(JTable table, int margin) {
        for (int c = 0; c < table.getColumnCount(); c++) {
            packColumn(table, c, margin);
        }
    }
// Ajusta al ancho preferido de la columna visible especificada con vColIndex.
// La columna sera lo bastante ancha para mostrar el contenido de la celda mas ancha.

    public static void packColumn(JTable table, int vColIndex, int margin) {
        TableModel model = table.getModel();
        DefaultTableColumnModel colModel = (DefaultTableColumnModel) table.getColumnModel();
        TableColumn col = colModel.getColumn(vColIndex);
        int width = 0;            // Obtiene la anchura de la cabecera de la columna
        TableCellRenderer renderer = col.getHeaderRenderer();
        if (renderer == null) {
            renderer = table.getTableHeader().getDefaultRenderer();
        }
        Component comp = renderer.getTableCellRendererComponent(
                table, col.getHeaderValue(), false, false, 0, 0);
        width = comp.getPreferredSize().width;            // Obtiene el ancho maximo de la celda
        for (int r = 0; r < table.getRowCount(); r++) {
            renderer = table.getCellRenderer(r, vColIndex);
            comp = renderer.getTableCellRendererComponent(
                    table, table.getValueAt(r, vColIndex), false, false, r,
                    vColIndex);
            width = Math.max(width, comp.getPreferredSize().width);
        }
        width += 2 * margin;            // Configura a largura
        col.setPreferredWidth(width);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        grupoOpciones = new javax.swing.ButtonGroup();
        jPanel1 = new javax.swing.JPanel();
        radioTratamiento = new javax.swing.JRadioButton();
        radioBloque = new javax.swing.JRadioButton();
        radioDiferentes = new javax.swing.JRadioButton();
        radioIguales = new javax.swing.JRadioButton();
        jLabel1 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        tablaMs = new JTable() {
            @Override
            public void changeSelection(int rowIndex, int columnIndex,
                boolean toggle, boolean extend) {
                if (columnIndex == 0)
                // Podemos llamar a changeSelecion() incrementando la columna en 1
                // o bien podríamos hacer directamente un return.
                super.changeSelection(rowIndex, columnIndex + 1, toggle, extend);
                else
                super.changeSelection(rowIndex, columnIndex, toggle, extend);
            }
        };
        jLabel2 = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();

        setTitle("Valores para m");
        setIconImage(icono);

        jPanel1.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        radioTratamiento.setText("Un valor igual para cada Tratamiento (por columna)");
        radioTratamiento.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                radioTratamientoActionPerformed(evt);
            }
        });

        radioBloque.setText("Un valor igual para cada Bloque (por fila)");
        radioBloque.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                radioBloqueActionPerformed(evt);
            }
        });

        radioDiferentes.setText("Un valor diferente por celda");
        radioDiferentes.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                radioDiferentesActionPerformed(evt);
            }
        });

        radioIguales.setSelected(true);
        radioIguales.setText("Un valor igual para todas las celdas");
        radioIguales.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                radioIgualesActionPerformed(evt);
            }
        });

        jLabel1.setText("Escoja una opción para los valores");

        jScrollPane1.setMinimumSize(new java.awt.Dimension(500, 200));

        tablaMs.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {"Bloque 1", "", null, null, null},
                {"Bloque 2", "", null, null, null},
                {"Bloque ...", "", null, null, null},
                {"Bloque n", "", null, null, null}
            },
            new String [] {
                "", "Tratamiento 1", "Tratamiento 2", "Tratamiento ...", "Tratamiento k"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, true, true, true, true
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        tablaMs.setMaximumSize(new java.awt.Dimension(100, 100));
        tablaMs.setMinimumSize(new java.awt.Dimension(100, 100));
        tablaMs.getTableHeader().setReorderingAllowed(false);
        jScrollPane1.setViewportView(tablaMs);

        jLabel2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/view/gui/m_ij.png"))); // NOI18N
        jLabel2.setText(":");

        jButton1.setText("Aceptar");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton2.setText("cancelar");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 490, Short.MAX_VALUE)
                        .addContainerGap())
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(radioBloque)
                            .addComponent(radioDiferentes)
                            .addComponent(radioTratamiento)
                            .addComponent(radioIguales)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(jLabel1)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jLabel2))
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(jButton1)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jButton2)))
                        .addGap(0, 0, Short.MAX_VALUE))))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jLabel2))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(radioIguales)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(radioTratamiento)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(radioBloque)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(radioDiferentes)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 205, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton1)
                    .addComponent(jButton2))
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void radioBloqueActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_radioBloqueActionPerformed

        modeloBloques = new DefaultTableModel(
                new Object[filas][2],
                new String[]{" ", "Todos"}) {

            @Override
            public boolean isCellEditable(int row, int column) {
                if (0 == column) {
                    return false;
                }
                return super.isCellEditable(row, column);
            }
        };
        for (int i = 0; i < filas; i++) {
            modeloBloques.setValueAt("Bloque " + (i + 1), i, 0);

        }
        tablaMs.setModel(modeloBloques);


//        for (int i = 0; i < filas; i++) {
//            modeloTratamientos.setValueAt("fghjkl;oiuytrtyuiolkjhgbhnjmkjh", i, 1);
//        }
        tablaMs.getColumnModel().getColumn(0).setCellRenderer(
                tablaMs.getTableHeader().getDefaultRenderer());
        packColumns(tablaMs, 2);
    }//GEN-LAST:event_radioBloqueActionPerformed

    private void radioIgualesActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_radioIgualesActionPerformed
        modeloIguales = new DefaultTableModel(
                new Object[1][2],
                new String[]{" ", "Todos"
                }) {

            @Override
            public boolean isCellEditable(int row, int column) {
                if (0 == column) {
                    return false;
                }
                return super.isCellEditable(row, column);
            }
        };

        modeloIguales.setValueAt("Todos", 0, 0);
        modeloIguales.setValueAt(5, 0, 1);
        tablaMs.setModel(modeloIguales);
        tablaMs.getColumnModel().getColumn(0).setCellRenderer(
                tablaMs.getTableHeader().getDefaultRenderer());
    }//GEN-LAST:event_radioIgualesActionPerformed

    private void radioTratamientoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_radioTratamientoActionPerformed


        String titulosColumnas[] = new String[columnas + 1];
        titulosColumnas[0] = " ";
        for (int i = 1; i <= columnas; i++) {
            titulosColumnas[i] = "Tratamiento " + i;
        }
        modeloTratamientos = new DefaultTableModel(
                new Object[1][columnas + 1],
                titulosColumnas) {

            @Override
            public boolean isCellEditable(int row, int column) {
                if (0 == column) {
                    return false;
                }
                return super.isCellEditable(row, column);
            }
        };

        modeloTratamientos.setValueAt("Todos", 0, 0);
        tablaMs.setModel(modeloTratamientos);


//        for (int i = 1; i <= columnas; i++) {
//            modeloTratamientos.setValueAt("fghjkl;oiuytrtyuiolkjhgbhnjmkjh", 0, i);
//        }
        tablaMs.getColumnModel().getColumn(0).setCellRenderer(
                tablaMs.getTableHeader().getDefaultRenderer());
        packColumns(tablaMs, 2);
    }//GEN-LAST:event_radioTratamientoActionPerformed

    private void radioDiferentesActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_radioDiferentesActionPerformed
        String titulosColumnas[] = new String[columnas + 1];
        titulosColumnas[0] = " ";
        for (int i = 1; i <= columnas; i++) {
            titulosColumnas[i] = "Tratamiento " + i;
        }
        modeloDiferentes = new DefaultTableModel(
                new Object[filas][columnas + 1],
                titulosColumnas) {

            @Override
            public boolean isCellEditable(int row, int column) {
                if (0 == column) {
                    return false;
                }
                return super.isCellEditable(row, column);
            }
        };
        for (int i = 0; i < filas; i++) {
            modeloDiferentes.setValueAt("Bloque " + (i + 1), i, 0);

        }
        tablaMs.setModel(modeloDiferentes);
        tablaMs.getColumnModel().getColumn(0).setCellRenderer(
                tablaMs.getTableHeader().getDefaultRenderer());

    }//GEN-LAST:event_radioDiferentesActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        if (radioBloque.isSelected()) {
            metodo = MBLOQUES;
            System.out.println("seleccionado bloques");
            for (int i = 0; i < filas; i++) {
                for (int j = 0; j < columnas; j++) {
                    matrizM[i][j] = Integer.valueOf(modeloBloques.getValueAt(i, 1).toString());
                }
            }

        } else {
            if (radioDiferentes.isSelected()) {
                metodo = MDIFERENTES;
                System.out.println("seleccionado diferentes");
                for (int i = 0; i < filas; i++) {
                    for (int j = 0; j < columnas; j++) {
                        matrizM[i][j] = Integer.valueOf(modeloDiferentes.getValueAt(i, j + 1).toString());
                    }
                }
            } else {
                if (radioIguales.isSelected()) {
                    metodo = MIGUALES;
                    System.out.println("seleccionado iguales");
                    System.out.println(modeloIguales.getValueAt(0, 1).toString());
                    for (int i = 0; i < filas; i++) {
                        for (int j = 0; j < columnas; j++) {
                            matrizM[i][j] = Integer.valueOf(modeloIguales.getValueAt(0, 1).toString());
                        }
                    }
                } else {
                    if (radioTratamiento.isSelected()) {
                        System.out.println("seleccionado tratamiento");
                        metodo = MTRATAMIENTOS;
                        for (int i = 0; i < filas; i++) {
                            for (int j = 0; j < columnas; j++) {
                                matrizM[i][j] = Integer.valueOf(modeloTratamientos.getValueAt(0, j + 1).toString());
                            }
                        }
                    }

                }
            }
        }

        resultado = true;
        this.setVisible(false);
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        resultado=false;
        this.setVisible(false);
    }//GEN-LAST:event_jButton2ActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(IngresoM_ij.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(IngresoM_ij.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(IngresoM_ij.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(IngresoM_ij.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the dialog
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                IngresoM_ij dialog = new IngresoM_ij(new javax.swing.JFrame(), true, 20, 20);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {

                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.ButtonGroup grupoOpciones;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JRadioButton radioBloque;
    private javax.swing.JRadioButton radioDiferentes;
    private javax.swing.JRadioButton radioIguales;
    private javax.swing.JRadioButton radioTratamiento;
    private javax.swing.JTable tablaMs;
    // End of variables declaration//GEN-END:variables
}
